package com.clb.studyproject.ui

import android.Manifest
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.media.MediaScannerConnection
import android.net.Uri
import android.os.Bundle
import android.os.Environment
import android.util.Log
import android.widget.Button
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.ContextCompat
import com.clb.studyproject.R
import java.io.File
import java.io.FileOutputStream
import java.util.*

class SavePicToLocalActivity : AppCompatActivity(R.layout.activity_save_pic_to_local) {

    private val PERMISSION_WRITH_STORAGE = 0x1001
    private lateinit var imgShow: ImageView
    private val TAG = javaClass.name

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        imgShow = findViewById<ImageView>(R.id.img_show)
        findViewById<Button>(R.id.save_to_local).setOnClickListener {
            checkPermission()
        }

    }

    fun checkPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), PERMISSION_WRITH_STORAGE)
        } else {
            saveToLocal()
        }
    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        when (requestCode) {
            PERMISSION_WRITH_STORAGE -> {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    saveToLocal()
                } else {
                    Toast.makeText(this, "获取存储权限失败", Toast.LENGTH_SHORT).show()
                }
            }
            else -> {
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
    }

    private fun saveToLocal() {
        try {
            val storageState = Environment.getExternalStorageState()
            if (storageState.equals(Environment.MEDIA_MOUNTED).not()) {
                Toast.makeText(this, "外部存储卡不可用", Toast.LENGTH_SHORT).show()
                return
            }
            imgShow.isDrawingCacheEnabled = true
            val bitmap = imgShow.drawingCache

            val dir = getExternalFilesDir(Environment.DIRECTORY_PICTURES)?.path + "/studyFile/"
            val fileName = UUID.randomUUID().toString() + ".jpg"
            //判断文件是否存在
            val file = File(dir + fileName)
            val file1 = File(dir)

            if (file1.exists().not()) {
                val mkdirs = file1.mkdirs()
                if (mkdirs) {
                    runOnUiThread {
                        Toast.makeText(this, "文件夹创建成功", Toast.LENGTH_SHORT).show()
                    }
                    Log.d(TAG, "saveToLocal: 文件已创建：$file1")
                } else {
                    runOnUiThread {
                        Toast.makeText(this, "文件夹创建失败", Toast.LENGTH_SHORT).show()
                    }
                    Log.d(TAG, "saveToLocal: 文件创建失败：$file1")
                }
            }
            val outputStream = FileOutputStream(file)
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outputStream)
            outputStream.flush()
            outputStream.close()
            imgShow.isDrawingCacheEnabled = false
            runOnUiThread {
                Toast.makeText(this, "文件保存成功：${file.path}", Toast.LENGTH_SHORT).show()
            }
            val fromFile = Uri.fromFile(file)
            MediaScannerConnection.scanFile(this, arrayOf(dir),null,null)
            sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, fromFile))
        } catch (e: Exception) {
            e.printStackTrace()
        }
    }

}
